﻿@model Kooboo.CMS.Web.Areas.Sites.Models.ResourceGridModel
@{
    ViewBag.Title = ViewData["Title"];
    Layout = "~/Views/Shared/Site.cshtml";

    var routes = ViewContext.RequestContext.AllRouteValues();

    string type = ViewContext.RequestContext.GetRequestValue("type").ToLower();

    var folderPath = ViewContext.RequestContext.GetRequestValue("folderPath");
    var folderPaths = new string[0];
    if (!string.IsNullOrEmpty(folderPath))
    {
        folderPaths = folderPath.Split(new char[] { '\\' });
    }
}
@section Panel{
    <ul class="panel">
        <li><a href="@Html.Raw(this.Url.Action("CreateFile", routes.Merge("return", ViewContext.HttpContext.Request.RawUrl))) ">@Html.IconImage("add")@("New file".Localize())</a></li>
        <li><a id="CreateFolder">@Html.IconImage("add-folder")@("New folder".Localize())</a></li>
        <li>
            <a href="@Url.Action("Import", routes.Merge("return", ViewContext.HttpContext.Request.RawUrl).Merge("title", "Import " + type))">
                @Html.IconImage("import") @("Import".Localize())
            </a>
        </li>
        <li>
            <a class="upload-button">
                <span>
                    <form action="@Html.Raw(this.Url.Action("Upload", routes))" enctype="multipart/form-data" method="post" class="no-stop">
                        <input type="file" name="file" title="@("Upload".Localize())" />
                    </form>
                </span>
                @Html.IconImage("upload")@("Upload".Localize())
            </a>
        </li>
        <li><a href="@Html.Raw(this.Url.Action("Delete", routes))" data-show-on-check="Any" data-show-on-selector=".localized" data-command-type="AjaxPost"  data-confirm="@("Are you sure you want to delete these items?".Localize())">@Html.IconImage("delete") @("Delete".Localize())</a></li>
        <li class="j_DropDown" data-show-on-check="Any">
            <a>
                @("More...".Localize())
                @Html.IconImage("arrow small white-down")
            </a>
            <ul class="j_DropDownContent hide">
                <li><a href="@Url.Action("Localize", ViewContext.RequestContext.AllRouteValues().Merge("return", ViewContext.HttpContext.Request.RawUrl))" data-show-on-check="Any" data-show-on-selector=".unlocalized" data-command-type="AjaxPost">
                    @("Localize".Localize())</a></li>

                <li>
                    <a href="@Url.Action("Export", ViewContext.RequestContext.AllRouteValues().Merge("return", ViewContext.HttpContext.Request.RawUrl))" data-show-on-check="Any" data-show-on-selector=".localized"  data-command-type="Download">
                        @("Export".Localize())
                    </a>
                </li>
                <li><a id="RenameButton" data-show-on-check="Single" data-show-on-selector=".localized">@("Rename".Localize())</a></li>
            </ul>
        </li>
        @foreach (var group in Kooboo.CMS.Sites.Extension.UI.TopToolbar.ToolbarButtons.GetToolbarButtons(ViewContext.RequestContext))
        {
            @Html.Partial("_ToolbarGroupButtons", group)
        }
    </ul>
}
<div class="topbar clearfix">
    <h1 class="title">
        @ViewBag.Title </h1>
    @if (folderPaths.Length > 0)
    {
        <div class="breadcrumb">
            <a href="@Url.Action("Index", ViewContext.RequestContext.AllRouteValues().Merge("folderPath", ""))">@("Root".Localize())</a>
            @Html.IconImage("arrow gray-right")
            @for (var i = 0; i < folderPaths.Length; i++)
            {
                if (i == folderPaths.Length - 1)
                {
                <span>@folderPaths[i]</span>
                }
                else
                {
                <a href="@Url.Action("Index", ViewContext.RequestContext.AllRouteValues().Merge("folderPath", string.Join("\\", folderPaths.Take(i + 1))))">@folderPaths[i]</a>
                @Html.IconImage("arrow gray-right")
                }
            }
        </div>
    }
</div>
@helper RenderHeader()
{
    <thead>
        <tr>
            <th class="checkbox mutiple">
                <div>
                    <input type="checkbox" class="select-all" />
                    <ul class="hide">
                        <li>Select:</li>
                        <li class="all"><a>
                            @("All Elements".Localize())</a></li>
                        <li class="docs"><a>
                            @("Only Documents".Localize())</a></li>
                        <li class="folders"><a>
                            @("Only Folders".Localize())</a></li>
                        <li class="none"><a>
                            @("None".Localize())</a></li>
                    </ul>
                </div>
            </th>
            <th class="common">
                @("Name".Localize())
            </th>
            <th>@("Path".Localize())</th>
            <th>@("Site".Localize())</th>
            <th class="date">
                @("Date".Localize())
            </th>
            <th class="size">
                @("Size".Localize())
            </th>
        </tr>
    </thead>
}
<div class="common-table fixed">
    <div class="thead">
        <table>
            @RenderHeader()
        </table>
    </div>
    <div class="tbody">
        <table>
            @RenderHeader()
            <tbody>
                <tr id="CreateFolderTemplate" class="hide">
                    <td class="checkbox"></td>
                    <td>
                        @using (Html.BeginForm(ViewContext.RequestContext.AllRouteValues().Merge("action", "CreateFolder").Merge("return", ViewContext.HttpContext.Request.RawUrl)))
                        {
                            <input class="editor" type="text" name="FolderName"
                                @(new[] { Validator.Regex(RegexPatterns.FileName,"Invalid folder name.".Localize()).ClientValidationRule,  Validator.Required().ClientValidationRule, 
                                ValidatorExtensions.Remote(Url.Action("IsFolderNameAvailable", routes), "The name already exists.".Localize()) }.GenerateHtmlAttributes())/>
                            <a class="action" data-ajaxform="">@Html.IconImage("save small")</a>
                            <a class="action" data-inline-action='{"hide":"#CreateFolderTemplate"}'>@Html.IconImage("minus small")</a>
                            @Html.ValidationMessageForInput("FolderName")
                        }
                    </td>
                    <td>@folderPath</td>
                    <td class="date"></td>
                    <td class="size"></td>
                </tr>
                @{
                    var dirs = Model.Directories.ToArray();
                    var files = Model.Files.ToArray();
                }
                @if (dirs.Length == 0 && files.Length == 0)
                { 
                    <tr class="empty">
                        <td colspan="100">
                            @("Empty".Localize())
                        </td>
                    </tr>
                }
                else
                {
                    foreach (var folder in dirs)
                    {
                        var templateId = "folder_" + UniqueIdGenerator.GetInstance().GetBase32UniqueId(10);
                        var displayTemplateId = templateId + "_display";
                        var editorTemplateId = templateId + "_editor";
                        var isLocalized = folder.Site == Site.Current;
                    <tr class="foldertr @(isLocalized ? "localized" : "unlocalized")">
                        <td class="checkbox">
                            <input type="checkbox" class="select folder" value="@folder.RelativePath" @(isLocalized ? "" : "disabled") />
                        </td>
                        <td class="common">
                            <div id="@displayTemplateId" class="display-template">
                                <a class="text" href="@Html.Raw(this.Url.Action("Index", ViewContext.RequestContext.AllRouteValues().Merge("folderPath", folder.RelativePath)))">@Html.IconImage("folder")@folder.Name</a>
                                @if (isLocalized)
                                {
                                    <a data-tr-hover="true" data-inline-action='{"show":"#@editorTemplateId","hide":"#@displayTemplateId"}' class="action hide">@Html.IconImage("edit small")</a>
                                }
                            </div>
                            <div id="@editorTemplateId" class="edit-template hide">
                                @using (Html.BeginForm(ViewContext.RequestContext.AllRouteValues().Merge("action", "RenameFolder").Merge("folderPath", folder.RelativePath)))
                                {
                                    <input type="text" name="FolderName" class="editor" value="@folder.Name" 
                                        @(new[] { Validator.Regex(RegexPatterns.FileName,"Invalid file name.".Localize()).ClientValidationRule,
                                        Validator.Required().ClientValidationRule,
                                        ValidatorExtensions.Remote(Url.Action("IsFolderNameAvailable", ViewContext.RequestContext.AllRouteValues()), "") }.GenerateHtmlAttributes())/>
                                    <a class="action" data-ajaxform="">@Html.IconImage("save small")</a>
                                    <a class="action" data-inline-action='{"show":"#@displayTemplateId","hide":"#@editorTemplateId"}'>@Html.IconImage("minus small")</a>
                                    @Html.ValidationMessageForInput("FolderName")
                                }
                            </div>

                        </td>
                        <td>@(string.IsNullOrEmpty(folderPath) ? "-" : "")</td>
                        <td>@(folder.Site)</td>
                        <td class="date">
                            @folder.LastUpdateDate.ToShortDateString()
                        </td>
                        <td class="size">-</td>
                    </tr>
                    }
                    foreach (var content in files)
                    {
                        var extension = string.IsNullOrWhiteSpace(content.FileExtension) ? "unknown" : content.FileExtension.TrimStart('.');
                        var templateId = "file_" + UniqueIdGenerator.GetInstance().GetBase32UniqueId(10);
                        var displayTemplateId = templateId + "_display";
                        var editorTemplateId = templateId + "_editor";
                        var isLocalized = content.Site == Site.Current;
                    <tr class="doctr @(extension) @(isLocalized ? "localized" : "unlocalized")">
                        <td class="checkbox draggable">
                            <div>
                                @Html.IconImage("drag")
                                <input type="checkbox" class="select doc" value="@content.RelativePath" data-filename="@content.FileName"/>
                            </div>
                        </td>
                        <td class="common">

                            <div id="@displayTemplateId" class="display-template">
                                @if (content.CanBeEdit && isLocalized)
                                {
                                    <a class="text" href="@Html.Raw(this.Url.Action("EditFile", ViewContext.RequestContext.AllRouteValues().Merge("relativePath", content.RelativePath).Merge("return", Request.RawUrl)))">@Html.IconImage("file " + extension)@content.FileName</a>
                                }
                                else if (content.IsImage)
                                {
                                    <a class="text" href="@Url.Content(content.VirtualPath)" target="_blank">@Html.IconImage("file image " + extension)@content.FileName</a>
                                }
                                else
                                {
                                    <a class="text" href="@Url.Content(content.VirtualPath)" target="_blank">@Html.IconImage("file " + extension)@content.FileName</a>
                                }
                                @if (isLocalized)
                                {
                                    <a data-tr-hover="true" data-inline-action='{"show":"#@editorTemplateId","hide":"#@displayTemplateId"}' class="action hide">@Html.IconImage("edit small")</a>
                                }
                            </div>
                            <div id="@editorTemplateId" class="edit-template hide">
                                @using (Html.BeginForm(ViewContext.RequestContext.AllRouteValues().Merge("action", "RenameFile").Merge("relativePath", content.RelativePath)))
                                {
                                    <input type="text" name="FileName" class="editor" value="@content.FileName" 
                                        @(new[] { Validator.Required().ClientValidationRule, ValidatorExtensions.Remote(Url.Action("IsFileNameAvailable", ViewContext.RequestContext.AllRouteValues()), "") }.GenerateHtmlAttributes())/>
                                    <a class="action" data-ajaxform="">@Html.IconImage("save small")</a>
                                    <a class="action" data-inline-action='{"show":"#@displayTemplateId","hide":"#@editorTemplateId"}'>@Html.IconImage("minus small")</a>
                                    @Html.ValidationMessageForInput("FileName")
                                }
                            </div>

                        </td>
                        <td>
                            @content.RelativePath
                        </td>
                        <td>@content.Site</td>
                        <td class="date">
                            @content.CreateDate.ToShortDateString()
                        </td>
                        <td class="size">
                            @content.FileSize B
                        </td>
                    </tr>
                    }
                }
            </tbody>
        </table>
    </div>
</div>
<script>
    $(function () {
        var table = $('.common-table table');
        table.checkableTable();
        table.mixedGrid();
        table.gridInlineEdit();

        $('#CreateFolder').click(function () {
            $('#CreateFolderTemplate').removeClass('hide');
            $('.empty').hide();
        });

        $('#RenameButton').click(function () {
            var $selected = table.find("tbody tr input:checkbox[checked]");
            var $td = $selected.closest('td').next();
            $td.find('.display-template').addClass('hide');
            $td.find('.edit-template').removeClass('hide');
        });
        (function () {
            table.find("tbody tr.doctr").css("cursor", "move");
            table.find("tbody").sortable({
                helper: fixHelper,
                items: "tr.doctr",
                handle: 'td.draggable .drag',
                update: function (event, ui) {

                    var fileOrders = {};
                    _.each($('[data-filename]').toArray(), function (item, index) {
                        var $item = $(item);
                        var p = 'fileNames[' + index + ']';
                        fileOrders[p] = $item.data('filename');
                    });

                    $.ajax({
                        url: '@Html.Raw(this.Url.Action("Sort", ViewContext.RequestContext.AllRouteValues()))',
                        data: fileOrders,
                        type: 'post',
                        beforeSend: function () {
                            window.loading.show();
                        },
                        success: function (response) {
                            if (response.Success) {
                            } else {
                                kooboo.cms.ui.messageBox().showResponse(response);
                            }
                            window.loading.hide();
                        },
                        error: function () {
                        }
                    });
                }
            });
        }());
    });
</script>

